package com.hjj.web.core;

import com.google.common.util.concurrent.RateLimiter;
import com.hjj.web.entity.vo.WebsocketUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Mirro
 */
@Slf4j
@Component
@Profile("!unittest")
public class WebSocketInterceptor extends ChannelInterceptorAdapter {
    @Autowired
    private QuartzService quartzService;

    private static final RateLimiter rateLimiter = RateLimiter.create(1);

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            log.info("请求websocket建立连接....");
            boolean isAllow = rateLimiter.tryAcquire(3, TimeUnit.SECONDS);
            if (!isAllow) {
                throw new RuntimeException("请求建立websocket连接太频繁，请稍后重试");
            }
            Object raw = message.getHeaders().get(SimpMessageHeaderAccessor.NATIVE_HEADERS);
            if (raw instanceof Map) {
                // Object authorizationObj = ((Map) raw).get("Authorization");
                // if (authorizationObj instanceof LinkedList) {
                //     String authorization = ((LinkedList) authorizationObj).get(0).toString();
                //     resourceAuthenticationManager.customAuthenticate(authorization);
                //     UserInfo userInfo = UserContext.getUserInfoContext();
                //     if (Objects.isNull(userInfo)) {
                //         return null;
                //     }
                // }
                Object sessionIdObj = ((Map) raw).get("userName");
                log.info("sessionIdObj=" + sessionIdObj.toString());
                if (sessionIdObj instanceof LinkedList) {
                    String sessionId = ((LinkedList) sessionIdObj).get(0).toString();
                    log.info("sessionId=" + sessionIdObj);
                    if (StringUtils.isBlank(sessionId)) {
                        return null;
                    }
                    //设置当前访问器的认证用户
                    accessor.setUser(new WebsocketUserVO(sessionId));
                }
            }
        } else if (StompCommand.DISCONNECT.equals(accessor.getCommand())) {
            log.info("websocket断开连接");
            WebsocketUserVO vo = (WebsocketUserVO) message.getHeaders().get(SimpMessageHeaderAccessor.USER_HEADER);
            if (Objects.nonNull(vo)) {
               /* try {
                    WsSessionManager.remove(vo.getName());
                } catch (Exception e) {
                    log.error("删除websocket连接失败，失败信息：{}", ExceptionUtils.getStackTrace(e));
                }*/
                quartzService.deleteJob(vo.getName());
            }
        }
        return message;
    }
}
